package util.BReceiverUtil;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.SmsMessage;
import android.util.Log;

/**
 * Created by Administrator on 2016/7/27.
 * 接收验证码短信的广播
 */
public class SMSBroadcastReceiver extends BroadcastReceiver{
    private IMessageListener mIMessageListener;
    public static final String SMS_RECEIVED_ACTION = "android.provider.Telephony.SMS_RECEIVED";//只要注册声明权限即可收到、阻断想要阻断短信通知必须成为系统默认短信应用

    public SMSBroadcastReceiver(){
        super();
    }

    @Override public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(SMS_RECEIVED_ACTION)) {
            Object[] pdus = (Object[]) intent.getExtras().get("pdus");
            for(Object pdu:pdus) {
                SmsMessage smsMessage = SmsMessage.createFromPdu((byte [])pdu);
                String sender = smsMessage.getDisplayOriginatingAddress();  //电话号码
                Log.e("sender",sender);
                //短信内容
                String content = smsMessage.getDisplayMessageBody();
                 if(content.length() > 3){
                     if(content.substring(1,3).equals("牛郎")){
                         String string = content.substring(content.length()-5,content.length());
                         mIMessageListener.onReceived(string);
                         abortBroadcast();
                     }
                 }
            }
        }
    }

    /**
     * 回调接口
     */
    public interface IMessageListener {
        void onReceived(String message);
    }

    public void setOnReceivedMessageListener(IMessageListener messageListener) {
        this.mIMessageListener = messageListener;
    }
}
